Unit Testing



# Description:

Unit Testing is a software testing method where individual components or functions of a program are tested separately to ensure they work correctly. It is usually automated and helps detect bugs early in development. Tools like JUnit and pytest are commonly used to improve code quality and reliability.

Think of your program as a machine made of many small parts. Unit testing checks each part separately to confirm it does exactly what it’s supposed to do.



# Why Unit Testing?

Unit testing isn’t just a “nice-to-have” it solves very real problems you’ll hit as your app grows. It is needed because it protects your code from breaking and helps you build reliable software faster. Here’s why it matters in practical terms:


It may feel like extra work at first, but it prevents:

  • Repeated manual testing
  • Long debugging sessions
  • Production issues


As you write enough code determining which section broke can be time consuming. These tests can you give you an idea which units/sections are working fine and which are breaking.


Writing unit tests forces you to:

  • Keep functions small
  • Avoid tight coupling
  • Write predictable logic
  • More modular systems


When you test small pieces (functions/components), you detect issues immediately after writing code



# Examples of Unit Testing

function add(a, b) {
    return a + b;
}

Test case:

test('adds 2 + 3 to equal 5', () => {
    expect(add(2, 3)).toBe(5);
}

function divide(a, b) {
    if (b === 0) return null;
    return a / b;
}

Test case:

test('returns null when dividing by zero', () => {
    expect(divide(5, 0)).toBe(null);
}

function Greeting({ name }) {
    return <h1>Hello {name}</h1>;
}

Test case:

import { render, screen } from '@testing-library/react';

test('renders greeting', () => {
    render(<Greeting name='xyz' />);
    expect(screen.getByText('Hello xyz')).toBeInTheDocument();
}

function User() {
    const [name, setName] = React.useState(');

    React.useEffect(() => {
        fetch('/api/user')
          .then(res => res.json())
          .then(data => setName(data.name));
        }, []);
    return <p>{name || 'Loading...'}</p>;
}

Test case:

import { render, screen, waitFor } from '@testing-library/react';

global.fetch = jest.fn(() =>
    Promise.resolve({
        json: () => Promise.resolve({ name: 'xyz' }),
    })
);

test('fetches and displays user', async () => {
    render(<User />);

    await waitFor(() => {
        expect(screen.getByText('xyz')).toBeInTheDocument();
    });
});


# How to get it done?

We have shared our view here and thats what most organisations follow:

Define a strategy

  • What to test (functions, APIs, UI components)
  • What NOT to test (e.g., third-party libraries)
  • Coverage goals

Depends on Language:

Frontend (React)

  • Jest
  • React Testing Library (RTL)

Backend

  • JUnit
  • pytest

Typical flow:

  • Developer pushes the unit testing code they wrote
  • CI tool (e.g., Jenkins) runs tests
  • If tests fail: build fails
  • If tests pass: code can be merged

Go through all sessions (Coming Soon...)